package CompressTool

import (
	"archive/zip"
	"gitee.com/dadjin/my-commonly-used-go-func/MyTool/FileTool"
	"io"
	"os"
	"path/filepath"
)

/*
用法:
// 要压缩的文件夹路径
	source := "E:\\zscache\\sb.php"

	// 压缩文件保存路径
	destination := "E:\\zscache\\sb.zip"

	err := Zip(source, destination)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("压缩成功")
	}
*/
func ZipCompress(source string, destination string) error {
	zipFile, err := os.Create(destination)
	if err != nil {
		return err
	}
	defer zipFile.Close()

	zipWriter := zip.NewWriter(zipFile)
	defer zipWriter.Close()

	if FileTool.IsDir(source) {
		err = filepath.Walk(source, func(filePath string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}

			// 获取相对路径
			relPath, err := filepath.Rel(source, filePath)
			if err != nil {
				return err
			}
			// 在压缩文件中创建该文件的对应目录和文件
			zipEntryName := filepath.ToSlash(relPath)

			zipEntryName = filepath.Join(filepath.Base(source), zipEntryName) // 将目录添加到根目录下

			if info.IsDir() {
				zipEntryName += "/"
				_, err = zipWriter.Create(zipEntryName)
			} else {
				err = addFileToZip(zipWriter, filePath, zipEntryName, info)
			}
			return err
		})
	} else {
		_, sourceFileName := filepath.Split(source)
		err = addFileToZip(zipWriter, source, sourceFileName, nil)
	}

	return err
}

func addFileToZip(zipWriter *zip.Writer, filePath string, zipEntryName string, info os.FileInfo) error {

	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	writer, err := zipWriter.Create(zipEntryName)
	if err != nil {
		return err
	}

	_, err = io.Copy(writer, file)
	return err
}
